import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
// import NProgress from 'nprogress'  // 禁用进度条
import { useAppStore } from '@/stores'
import { useMenuStore } from '@/stores/menu'
import { dynamicRoutes } from './dynamicRoutes'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: () => import('@/Layout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'fa-dashboard' }
      },
      {
        path: 'cmdb/hosts',
        name: 'HostManagement',
        component: () => import('@/views/hosts/HostManagement.vue'),
        meta: { title: '主机管理', icon: 'fa-server', parent: 'CMDB资产管理' }
      },

      {
        path: 'cmdb/hostgroups',
        name: 'HostGroups',
        component: () => import('@/views/hostgroups/Index.vue'),
        meta: { title: '主机组管理', icon: 'fa-object-group', parent: 'CMDB资产管理' }
      },
      {
        path: 'cmdb/hosttypes',
        name: 'HostTypes',
        component: () => import('@/views/hosts/HostTypeManagement.vue'),
        meta: { title: '主机类型管理', icon: 'fa-tags', parent: 'CMDB资产管理' }
      },
      {
        path: 'cmdb/connections',
        name: 'HostConnections',
        component: () => import('@/views/connections/Index.vue'),
        meta: { title: '连接主机', icon: 'fa-terminal', parent: 'CMDB资产管理' }
      },
      {
        path: 'cmdb/user/management',
        name: 'UserManagement',
        component: () => import('@/views/user/UserManagement.vue'),
        meta: { title: '用户管理', icon: 'fa-user' }
      },
      {
        path: 'cmdb/user/groups',
        name: 'UserGroupManagement',
        component: () => import('@/views/user/UserGroupManagement.vue'),
        meta: { title: '用户组管理', icon: 'fa-users' }
      },
      {
        path: 'cmdb/user/roles',
        name: 'RoleManagement',
        component: () => import('@/views/user/RoleManagement.vue'),
        meta: { title: '角色管理', icon: 'fa-user-tag' }
      },
      {
        path: 'cmdb/user/menu-permission',
        name: 'MenuPermissionManagement',
        component: () => import('@/views/user/MenuPermissionManagement.vue'),
        meta: { title: '菜单权限管理', icon: 'fa-key' }
      },
      {
        path: 'users/detail/:id',
        name: 'UserDetail',
        component: () => import('@/views/users/Detail.vue'),
        props: true,
        meta: { title: '用户详情', icon: 'fa-user' }
      },


      // Ansible管理路由 - 平级路由避免嵌套问题
      {
        path: 'ansible/config',
        name: 'AnsibleConfig',
        component: () => import('@/views/ansible/SimpleConfig.vue'),
        meta: { title: 'Ansible配置管理', icon: 'fa-cogs' }
      },
      {
        path: 'ansible/inventory',
        name: 'AnsibleInventory',
        component: () => import('@/views/ansible/SimpleInventory.vue'),
        meta: { title: 'Ansible Inventory管理', icon: 'fa-server' }
      },
      {
        path: 'ansible/adhoc',
        name: 'AnsibleAdhoc',
        component: () => import('@/views/ansible/SimpleAdhoc.vue'),
        meta: { title: 'Ansible Ad-hoc执行', icon: 'fa-bolt' }
      },
      {
        path: 'ansible/playbook',
        name: 'AnsiblePlaybook',
        component: () => import('@/views/ansible/PlaybookExecution.vue'),
        meta: { title: 'Ansible Playbook执行', icon: 'fa-file-code-o' }
      },
      {
        path: 'ansible/credentials',
        name: 'AnsibleCredentials',
        component: () => import('@/views/ansible/CredentialManagement.vue'),
        meta: { title: 'Ansible凭据管理', icon: 'fa-key' }
      },

      // Zabbix管理路由
      {
        path: 'zabbix/servers',
        name: 'ZabbixServers',
        component: () => import('@/views/zabbix/ZabbixServers.vue'),
        meta: { title: '服务器配置', icon: 'fa-server', parent: 'Zabbix管理' }
      },
      {
        path: 'zabbix/dashboard',
        name: 'ZabbixDashboard',
        component: () => import('@/views/zabbix/ZabbixDashboard.vue'),
        meta: { title: '监控仪表板', icon: 'fa-dashboard', parent: 'Zabbix管理' }
      },
      {
        path: 'zabbix/hosts',
        name: 'ZabbixHosts',
        component: () => import('@/views/zabbix/ZabbixHosts.vue'),
        meta: { title: '主机监控', icon: 'fa-desktop', parent: 'Zabbix管理' }
      },
      {
        path: 'zabbix/alerts',
        name: 'ZabbixAlerts',
        component: () => import('@/views/zabbix/ZabbixAlerts.vue'),
        meta: { title: '告警管理', icon: 'fa-bell', parent: 'Zabbix管理' }
      },
      {
        path: 'zabbix/templates',
        name: 'ZabbixTemplates',
        component: () => import('@/views/zabbix/ZabbixTemplates.vue'),
        meta: { title: '模板管理', icon: 'fa-file-code', parent: 'Zabbix管理' }
      },
      {
        path: 'zabbix/items',
        name: 'ZabbixItems',
        component: () => import('@/views/zabbix/ZabbixItems.vue'),
        meta: { title: '监控项管理', icon: 'fa-list-alt', parent: 'Zabbix管理' }
      },

      // Docker管理路由
      {
        path: 'docker/servers',
        name: 'DockerServers',
        component: () => import('@/views/docker/DockerServers.vue'),
        meta: { title: 'Docker服务器配置', icon: 'fa-server', parent: 'Docker管理' }
      },
      {
        path: 'docker/containers',
        name: 'DockerContainers',
        component: () => import('@/views/docker/DockerContainers.vue'),
        meta: { title: 'Docker容器管理', icon: 'fa-cube', parent: 'Docker管理' }
      },
      {
        path: 'docker/images',
        name: 'DockerImages',
        component: () => import('@/views/docker/DockerImages.vue'),
        meta: { title: 'Docker镜像管理', icon: 'fa-layer-group', parent: 'Docker管理' }
      },
      {
        path: 'docker/networks',
        name: 'DockerNetworks',
        component: () => import('@/views/docker/DockerNetworks.vue'),
        meta: { title: 'Docker网络管理', icon: 'fa-network-wired', parent: 'Docker管理' }
      },
      {
        path: 'docker/volumes',
        name: 'DockerVolumes',
        component: () => import('@/views/docker/DockerVolumes.vue'),
        meta: { title: 'Docker数据卷管理', icon: 'fa-hdd', parent: 'Docker管理' }
      },
      {
        path: 'docker/monitoring',
        name: 'DockerMonitoring',
        component: () => import('@/views/docker/DockerMonitoring.vue'),
        meta: { title: 'Docker容器监控', icon: 'fa-chart-line', parent: 'Docker管理' }
      },

      // Harbor镜像仓库管理路由
      {
        path: 'docker/registries',
        name: 'HarborRegistries',
        component: () => import('@/views/docker/DockerRegistries.vue'),
        meta: { title: 'Harbor镜像仓库配置', icon: 'fa-archive', parent: '镜像仓库管理' }
      },
      {
        path: 'harbor/projects',
        name: 'HarborProjects',
        component: () => import('@/views/docker/HarborProjects.vue'),
        meta: { title: 'Harbor项目管理', icon: 'fa-folder', parent: '镜像仓库管理' }
      },
      {
        path: 'harbor/images',
        name: 'HarborImages',
        component: () => import('@/views/docker/HarborImages.vue'),
        meta: { title: 'Harbor镜像管理', icon: 'fa-layer-group', parent: '镜像仓库管理' }
      },
      {
        path: 'harbor/audit-logs',
        name: 'HarborAuditLogs',
        component: () => import('@/views/docker/HarborAuditLogs.vue'),
        meta: { title: 'Harbor审计日志', icon: 'fa-file-text', parent: '镜像仓库管理' }
      },

      // DevOps管理路由
      {
        path: 'devops/gitlab/servers',
        name: 'GitLabServers',
        component: () => import('@/views/devops/gitlab/GitLabServers.vue'),
        meta: { title: 'GitLab服务器配置', icon: 'fa-server', parent: 'CICD管理' }
      },
      {
        path: 'devops/gitlab/projects',
        name: 'GitLabProjects',
        component: () => import('@/views/devops/gitlab/GitLabProjects.vue'),
        meta: { title: 'GitLab项目管理', icon: 'fa-folder', parent: 'CICD管理' }
      },
      {
        path: 'devops/gitlab/users',
        name: 'GitLabUsers',
        component: () => import('@/views/devops/gitlab/GitLabUsers.vue'),
        meta: { title: 'GitLab用户管理', icon: 'fa-users', parent: 'CICD管理' }
      },
      {
        path: 'devops/jenkins/servers',
        name: 'JenkinsServers',
        component: () => import('@/views/devops/jenkins/JenkinsServers.vue'),
        meta: { title: 'Jenkins服务器配置', icon: 'fa-server', parent: 'CICD管理' }
      },
      {
        path: 'devops/jenkins/jobs',
        name: 'JenkinsJobs',
        component: () => import('@/views/devops/jenkins/JenkinsJobs.vue'),
        meta: { title: 'Jenkins项目管理', icon: 'fa-tasks', parent: 'CICD管理' }
      },
      {
        path: 'devops/timeline',
        name: 'DevOpsTimeline',
        component: () => import('@/views/devops/DevOpsTimeline.vue'),
        meta: { title: 'DevOps操作时间线', icon: 'fa-clock-o', parent: 'CICD管理' }
      },

      // API测试页面
      {
        path: 'test/api',
        name: 'ApiTest',
        component: () => import('@/views/test/ApiTest.vue'),
        meta: { title: 'API测试', icon: 'fa-bug' }
      },
      {
        path: 'history/ssh-audit',
        name: 'SSHAudit',
        component: () => import('@/views/history/SSHAudit.vue'),
        meta: { title: 'SSH日志审计', icon: 'fa-terminal', parent: '历史记录' }
      },
      {
        path: 'history/ansible-audit',
        name: 'AnsibleAudit',
        component: () => import('@/views/history/AnsibleAudit.vue'),
        meta: { title: 'Ansible日志审计', icon: 'fa-tasks', parent: '历史记录' }
      },
      {
        path: 'history/gitlab-audit',
        name: 'GitLabAudit',
        component: () => import('@/views/history/GitLabAudit.vue'),
        meta: { title: 'GitLab集成历史', icon: 'fa-gitlab', parent: '历史记录' }
      },
      {
        path: 'history/jenkins-audit',
        name: 'JenkinsAudit',
        component: () => import('@/views/history/JenkinsAudit.vue'),
        meta: { title: 'Jenkins集成历史', icon: 'fa-jenkins', parent: '历史记录' }
      },
      {
        path: 'history/jenkins-builds-audit',
        name: 'JenkinsBuilds',
        component: () => import('@/views/history/JenkinsBuilds.vue'),
        meta: { title: 'Jenkins构建历史', icon: 'fa-cogs', parent: '历史记录' }
      },
      {
        path: 'history/sql-audit',
        name: 'SqlAudit',
        component: () => import('@/views/history/SqlAudit.vue'),
        meta: { title: 'SQL日志审计', icon: 'fa-database', parent: '历史记录' }
      },
      // SSH审计路由
      {
        path: 'audit',
        name: 'AuditDashboard',
        component: () => import('@/views/audit/AuditDashboard.vue'),
        meta: { title: 'SSH审计', icon: 'fa-shield' }
      },
      {
        path: 'audit/sessions',
        name: 'SessionList',
        component: () => import('@/views/audit/SessionList.vue'),
        meta: { title: '会话记录', icon: 'fa-history' }
      },
      {
        path: 'audit/commands',
        name: 'CommandList',
        component: () => import('@/views/audit/CommandList.vue'),
        meta: { title: '命令审计', icon: 'fa-terminal' }
      },
      {
        path: 'audit/replay/:sessionId',
        name: 'SessionReplay',
        component: () => import('@/views/audit/SessionReplay.vue'),
        meta: { title: '会话回放', icon: 'fa-play-circle' }
      },
      {
        path: 'system/menu-management',
        name: 'MenuManagement',
        component: () => import('@/views/system/MenuManagement.vue'),
        meta: { title: '菜单管理', icon: 'fa-list' }
      },
      {
        path: 'monitoring',
        name: 'Monitoring',
        component: () => import('@/views/monitoring/Index.vue'),
        meta: { title: '监控中心', icon: 'fa-line-chart' }
      },
      // 动态路由将在这里自动添加
      ...dynamicRoutes
    ]
  },



  // 兼容性重定向路由
  {
    path: '/hosts',
    redirect: '/cmdb/hosts'
  },
  {
    path: '/connections',
    redirect: '/cmdb/connections'
  },
  {
    path: '/users',
    redirect: '/cmdb/user/management'
  },

  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/ssh/:id',
    name: 'SSHTerminal',
    component: () => import('@/views/ssh/SSHTerminal.vue'),
    meta: { title: 'SSH终端', icon: 'fa-terminal' }
  },

  {
    path: '/test',
    name: 'Test',
    component: () => import('@/views/TestPage.vue'),
    meta: { title: '测试页面' }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue'),
    meta: { title: '404' }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 导航守卫
router.beforeEach(async (to, from, next) => {
  console.log('🚀 路由守卫开始:', to.path)

  // 设置文档标题
  document.title = to.meta?.title ? `${to.meta.title} - DevOps自动化运维系统` : 'DevOps自动化运维系统'

  // 检查认证
  const token = localStorage.getItem('token')
  console.log('🔑 检查token:', token ? '存在' : '不存在')

  // 如果访问登录或注册页面
  if (to.path === '/login' || to.path === '/register') {
    console.log('🔓 登录/注册页面，直接放行:', to.path)
    if (token) {
      // 已登录用户访问登录页，重定向到首页
      next({ path: '/' })
    } else {
      // 未登录用户正常访问登录页
      next()
    }
    return
  }

  // 对于不需要Layout的特殊路径，直接放行
  if (to.path === '/test' || to.path === '/404') {
    console.log('🔓 独立页面，直接放行:', to.path)
    next()
    return
  }

  // 如果访问其他页面但没有token，重定向到登录页
  if (!token) {
    console.log('❌ 无token，重定向到登录页')
    next({ path: '/login' })
    return
  }

  // 对于需要Layout的页面，确保基本数据已加载
  try {
    console.log('🏪 开始获取store...')
    const store = useAppStore()
    console.log('✅ store获取成功')

    // 如果用户信息未加载，先获取用户信息
    if (!store.userInfo) {
      await store.getUserInfo()
      console.log('成功获取用户信息:', store.userInfo)
    }

    // 使用新菜单系统加载菜单
    const menuStore = useMenuStore()
    if (menuStore.userMenus.length === 0 && !menuStore.menuLoading) {
      await menuStore.loadUserMenus()
      console.log('成功获取用户菜单:', menuStore.userMenus.length, '个菜单')
    }

    // 对于ansible、dashboard、system和menu路径，跳过权限检查直接放行
    if (to.path === '/dashboard' || to.path.startsWith('/ansible') || to.path.startsWith('/history') || to.path.startsWith('/system') || to.path.startsWith('/menu')) {
      console.log('🔓 特殊功能页面，跳过权限检查:', to.path)
      next()
      return
    }

    // 对于超级管理员，直接放行所有路径（绕过权限检查）
    if (store.userInfo?.is_superuser) {
      console.log('🔓 超级管理员，直接放行:', to.path)
      next()
      return
    }

    // 使用新菜单系统检查权限
    console.log('🔍 检查路径权限:', to.path)
    const hasPermission = menuStore.checkPathPermission(to.path)
    console.log('🔍 权限检查结果:', hasPermission)

    if (hasPermission) {
      console.log('✅ 权限通过，允许访问')
      next()
    } else {
      console.log('❌ 权限不足，重定向到404')
      next('/404')
    }
  } catch (error) {
    // 如果token无效或获取用户信息失败
    console.error('获取用户信息失败:', error)

    // 如果是429错误，不要立即跳转到登录页，而是显示提示
    if (error.response?.status === 429) {
      console.warn('请求频率过高，请稍后再试')
      // 暂时跳转到一个提示页面或者停留在当前页面
      next(false) // 取消导航
      return
    }

    const store = useAppStore()
    await store.logout()
    next({ path: '/login' })
  }
})

router.afterEach(() => {
  // NProgress.done()  // 禁用进度条
})

export default router
